package com.lixingqu.mvpdemo.ui.download;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.anthonycr.grant.PermissionsManager;
import com.anthonycr.grant.PermissionsResultAction;
import com.lixingqu.mvpdemo.R;
import com.lixingqu.mvpdemo.net.download.DbUtil;
import com.lixingqu.mvpdemo.net.download.DownInfo;
import com.lixingqu.mvpdemo.net.download.DownState;
import com.lixingqu.mvpdemo.net.download.HttpDownManager;
import com.lixingqu.mvpdemo.net.download.HttpDownOnNextListener;

import java.io.File;
import java.text.NumberFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DownloadActivity extends Activity {
    DbUtil dbUtil;
    String url = "http://www.izaodao.com/app/izaodao_app.apk";
    DownInfo downInfo;
    private HttpDownManager manager;
    @BindView(R.id.tv_progress)
    TextView mProgress;
    @BindView(R.id.tv_msg)
    TextView mMsg;

    private boolean isClick = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        ButterKnife.bind(this);
        checkPermission();
    }


    private void checkPermission() {
        String permission[] = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(DownloadActivity.this, permission, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                Log.i("lxq", "onGranted");
                initResource();
            }

            @Override
            public void onDenied(String permission) {
                Log.i("lxq", "onDenied");

            }
        });
    }

    private void initResource() {
        isClick = true;
        manager = HttpDownManager.getInstance();
        dbUtil = DbUtil.getInstance();

    }

    @OnClick({R.id.btn_download, R.id.btn_pause,R.id.btn_delete})
    public void myDownload(View view) {
        switch (view.getId()) {
            case R.id.btn_download:
                if (isClick) {
                    getNewDownloadTask(url);
                    if (downInfo.getState() != DownState.FINISH) {
                        Log.i("lxq", "click");
                        manager.startDown(downInfo);
                    }
                } else {
                    Toast.makeText(DownloadActivity.this, "未获取权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_pause:
                if (isClick) {
                    if (downInfo.getState()!=DownState.FINISH){
                        manager.pause(downInfo);
                    }else{
                        Toast.makeText(DownloadActivity.this, "已经下载完成，无法暂停", Toast.LENGTH_SHORT).show();
                    }
                    Log.i("lxq", "click");
                } else {
                    Toast.makeText(DownloadActivity.this, "未获取权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_delete:
                if (isClick){
                    manager.pause(downInfo);
                    manager.remove(downInfo);
                    mMsg.setText("下载进度");
                    mProgress.setText("");
                    dbUtil.deleteDowninfo(downInfo);
                    File file = new File(downInfo.getSavePath());
                    file.delete();
                    Toast.makeText(DownloadActivity.this, "任务已经重置", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(DownloadActivity.this, "未获取权限", Toast.LENGTH_SHORT).show();

                }
                break;
            default:
                break;
        }
    }


    public void getNewDownloadTask(String url){
        File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "test.apk");
        DownInfo queryDownInfo = dbUtil.queryDownInfoByUrl(url);
        if (queryDownInfo != null) {
            downInfo = queryDownInfo;
            mMsg.setText(downInfo.getState() + "");
            mProgress.setText(getPercent(downInfo.getReadLength(),downInfo.getCountLength())+"%");
        } else {
            downInfo = new DownInfo(url);
            downInfo.setState(DownState.START);
            downInfo.setSavePath(outputFile.getAbsolutePath());
            dbUtil.save(downInfo);
        }
        downInfo.setListener(httpProgressOnNextListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*记录退出时下载任务的状态-复原用*/
        if (downInfo != null) {
            dbUtil.update(downInfo);
        }
    }

    /*下载回调*/
    HttpDownOnNextListener<DownInfo> httpProgressOnNextListener = new HttpDownOnNextListener<DownInfo>() {
        @Override
        public void onNext(DownInfo baseDownEntity) {
            mMsg.setText("提示：下载完成");
            Toast.makeText(DownloadActivity.this, baseDownEntity.getSavePath(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStart() {
            mMsg.setText("提示:开始下载");
        }

        @Override
        public void onComplete() {
            mMsg.setText("提示：下载结束");
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            mMsg.setText("失败:" + e.toString());
        }


        @Override
        public void onPuase() {
            super.onPuase();
            mMsg.setText("提示:暂停");
        }

        @Override
        public void onStop() {
            super.onStop();
        }

        @Override
        public void updateProgress(long readLength, long countLength) {
            mMsg.setText("提示:下载中");
            mProgress.setText(getPercent(readLength,countLength)+"%");
        }
    };

    private String getPercent(long readLength, long countLength) {
        // 创建一个数值格式化对象

        NumberFormat numberFormat = NumberFormat.getInstance();

        // 设置精确到小数点后2位

        numberFormat.setMaximumFractionDigits(2);
        String result = numberFormat.format((float)readLength/(float)countLength * 100);
        return result;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
}
